import sys

from PySide6.QtCore import Slot
from PySide6.QtWidgets import QApplication, QFormLayout, QLabel, QPushButton, QTextEdit, QMessageBox, QLineEdit

from zz import zz_code, zz_mitmproxy, zz_log, zz_gui, zz_return

log = zz_log.of()


# 打包命令 pyinstaller -D -w ./chengtou_gui.py


class MainWindow(zz_gui.ZZ_Win):
    def __init__(self):
        proxy = zz_mitmproxy.of(allow_hosts=['qmai.cn'], file_path=f'{zz_code.dev_dir()}/qmai_mitm.py')
        super(MainWindow, self).__init__(proxy)
        # 设置窗口的关闭事件处理
        self.setWindowTitle("获取蒙自源token")
        # 参数依次为 x 坐标、y 坐标、宽度、高度
        self.setGeometry(300, 300, 500, 0)

        # 创建表单布局管理器
        layout = QFormLayout(self)
        # 添加按钮
        self.btn_listen = QPushButton('开启监听')
        self.btn_listen_close = QPushButton('关闭监听')

        # 创建标签和单行文本框
        lab_token = QLabel('Token:')
        self.txt_token = QTextEdit()
        self.lab_msg = QLabel('')
        # self.lab_msg_sub = QLabel('')

        # 添加标签和字段对，每一对成为布局中的一行，还有相应设列的函数
        layout.addRow(lab_token, self.txt_token)
        layout.addRow(self.btn_listen)
        layout.addRow(self.lab_msg)
        # layout.addRow(self.lab_msg_sub)

        # 添加水平和垂直方向的间隔
        layout.setHorizontalSpacing(15)
        layout.setVerticalSpacing(10)

        self.btn_listen.clicked.connect(self.start_mitmproxy)

    def start_mitmproxy(self):
        ok = super().start_mitmproxy()
        if ok:
            self.btn_listen.setDisabled(True)
            self.lab_msg.setText("正在启动..")

    def start_mitmproxy_finished(self, r: zz_return.Return):
        if r.err():
            self.btn_listen.setDisabled(False)
            self.lab_msg.setText("启动失败")
            return

        super().start_mitmproxy_finished(r)
        self.lab_msg.setText("监控中..")

    def listen_mitmproxy_finished(self, r: zz_return.Return):
        super().listen_mitmproxy_finished(r)

        token = r.get_data("token")
        self.lab_msg.setText("提示：token获取成功")
        self.txt_token.setText(token)
        self.btn_listen.setDisabled(False)
        log.info(r.to_json())

    @Slot()
    def closeEvent(self, event):
        # 弹出确认对话框
        reply = QMessageBox.question(self, '确认', '你确定要退出应用吗？',
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.close_mitmproxy()
            event.accept()  # 接受关闭事件
        else:
            event.ignore()  # 忽略关闭事件


def main():
    app = QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()
